import threading
from typing import Optional


def worker(step: int, lock: Optional[threading.Lock] = None) -> None:
    global g_num
    for _ in range(step):
        if lock:
            with lock:
                g_num += 1
                print(f"{threading.current_thread().name}: {g_num}")
        else:
            g_num += 1
            print(f"{threading.current_thread().name}: {g_num}")


def main(thread_count: int = 3, step: int = 10, use_lock: bool = True) -> None:
    global g_num
    g_num = 0
    lock = threading.Lock() if use_lock else None

    threads = [
        threading.Thread(target=worker, name=f"线程{i}", args=(step, lock))
        for i in range(thread_count)
    ]

    for thread in threads:
        thread.start()

    for thread in threads:
        thread.join()

    print(f"最终计数: {g_num}")


if __name__ == "__main__":
    main()  